package com.woyou.ui.adapter;

import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.squareup.picasso.Picasso;
import com.woyou.bean.ChosenGoods;
import com.woyou.bean.FillFooterGoods;
import com.woyou.bean.Goods;
import com.woyou.bean.OptionGroup;
import com.woyou.bean.ShopItem;
import com.woyou.model.GoodsModel;
import com.woyou.model.GoodsModel_;
import com.woyou.model.ShoppingCarModel;
import com.woyou.model.ShoppingCarModel_;
import com.woyou.ui.component.fastscroll.IViewHolder;
import com.woyou.ui.fragment.ShopInfoMenuLayout.LayoutControl;
import com.woyou.utils.CloneUtils;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventGoodsDetails;
import com.woyou.utils.eventbus.EventRefPrice;
import com.woyou.utils.eventbus.EventShoppingCarChange;
import com.woyou.utils.eventbus.EventShowDetails;

import de.greenrobot.event.EventBus;

/**
 * 商品列表的adapter
 * 
 * @author lenovo
 * 
 */
@SuppressLint("NewApi")
public class ShopMenuListAdapter extends BaseAdapter implements OnClickListener {
	
	private static final String TAG = "ShopMenuListAdapter";
	
	// private static final int refNum = 7;
	private Context context;
	private List<Object> data;
	// private int loadFlag = refNum;
	private ShopItem shopItem;
	private ShoppingCarModel shoppingCarModel;
	private GoodsModel mGoodsController;
	private Drawable tu;

	private LayoutControl mLayoutControl;
	
	public ShopMenuListAdapter(Context context, List<Object> data) {
		this.context = context;
		this.data = data;
		shoppingCarModel = ShoppingCarModel_.getInstance_(context);
		mGoodsController = GoodsModel_.getInstance_(context);
		Resources res = context.getResources();
		Bitmap bitmap = BitmapFactory.decodeResource(res, R.raw.tu);
		tu = new BitmapDrawable(res, bitmap);

	}

	public void setLayoutControl(LayoutControl control) {
		this.mLayoutControl = control;
	}

	/**
	 * 设置店铺状态
	 * 
	 * @param shopItem
	 */
	public void setShopItem(ShopItem shopItem) {
		this.shopItem = shopItem;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	ViewHolder viewHolder;

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.item_menulist_lv, null);
			viewHolder.goodsView = (RelativeLayout) convertView
					.findViewById(R.id.item_goods);
			viewHolder.iv = (ImageView) convertView
					.findViewById(R.id.item_menulist_lv_iv);
			viewHolder.heart=(ImageView)convertView.findViewById(R.id.item_menulist_heart);
			viewHolder.glass=(ImageView)convertView.findViewById(R.id.item_menulist_glass);
			viewHolder.mask = (ImageView) convertView
					.findViewById(R.id.item_menulist_lv_mask);
			viewHolder.name = (TextView) convertView
					.findViewById(R.id.item_menulist_lv_name);
			viewHolder.price = (TextView) convertView
					.findViewById(R.id.item_menulist_lv_price);
			viewHolder.detail = (ImageView) convertView
					.findViewById(R.id.item_menulist_lv_detail);
			viewHolder.add = (RelativeLayout) convertView
					.findViewById(R.id.item_menulist_lv_add);
			viewHolder.numview = (RelativeLayout) convertView
					.findViewById(R.id.item_menulist_lv_numview);
			viewHolder.num = (TextView) convertView
					.findViewById(R.id.item_menulist_lv_num);
			viewHolder.minus = (RelativeLayout) convertView
					.findViewById(R.id.item_menulist_lv_minus);
			viewHolder.choose = (ImageView) convertView
					.findViewById(R.id.item_menulist_lv_choose);
			viewHolder.na = (TextView) convertView
					.findViewById(R.id.item_menulist_lv_na);
			viewHolder.iv.setOnClickListener(this);
			viewHolder.goodsView.setOnClickListener(this);
			viewHolder.numview.setOnClickListener(this);
			viewHolder.add.setOnClickListener(this);
			viewHolder.minus.setOnClickListener(this);
			viewHolder.choose.setOnClickListener(this);
			viewHolder.detail.setOnClickListener(this);
			//
			viewHolder.chosenGoodsView = (RelativeLayout) convertView
					.findViewById(R.id.item_chosengoods);
			viewHolder.adjust = (LinearLayout) convertView
					.findViewById(R.id.shopmenu_child_adjust);
			viewHolder.cMaskBottom = (ImageView) convertView
					.findViewById(R.id.shopmenu_child_maskbottom);
			viewHolder.cName = (TextView) convertView
					.findViewById(R.id.shopmenu_child_name);
			viewHolder.cAdd = (ImageView) convertView
					.findViewById(R.id.shopmenu_child_add);
			viewHolder.cNum = (TextView) convertView
					.findViewById(R.id.shopmenu_child_num);
			viewHolder.cMinus = (ImageView) convertView
					.findViewById(R.id.shopmenu_child_minus);
			viewHolder.adjust.setOnClickListener(this);
			viewHolder.cAdd.setOnClickListener(this);
			viewHolder.cMinus.setOnClickListener(this);
			//
			viewHolder.menulist_lv_footer = (LinearLayout) convertView
					.findViewById(R.id.menulist_lv_footer);

			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		Log.i(TAG, "---------");
		Object object = data.get(position);
		viewHolder.position = position;
		if (object instanceof Goods) {
			viewHolder.goodsView.setVisibility(View.VISIBLE);
			viewHolder.chosenGoodsView.setVisibility(View.GONE);
			viewHolder.menulist_lv_footer.setVisibility(View.GONE);
			Goods goods = (Goods) object;
			onItemGoods(position, viewHolder, goods);
			//判断是否显示爱心
			if(goods.getSalesUrl()!=null&&!goods.getSalesUrl().equals("")){
				viewHolder.heart.setVisibility(View.VISIBLE);
			}else{
				viewHolder.heart.setVisibility(View.GONE);
			}
			//判断是否显示放大镜
			if(goods.getDetailPic()!=null&&!goods.getDetailPic().equals("")){
				viewHolder.glass.setVisibility(View.VISIBLE);
			}else{
				viewHolder.glass.setVisibility(View.GONE);
			}
		} else if (object instanceof ChosenGoods) {
			viewHolder.goodsView.setVisibility(View.GONE);
			viewHolder.chosenGoodsView.setVisibility(View.VISIBLE);
			viewHolder.menulist_lv_footer.setVisibility(View.GONE);
			ChosenGoods optionGoods = (ChosenGoods) object;
			viewHolder.optionGoods = optionGoods;
			onChosenGoods(viewHolder);
		} else if (object instanceof FillFooterGoods) {
			viewHolder.goodsView.setVisibility(View.GONE);
			viewHolder.chosenGoodsView.setVisibility(View.GONE);
			viewHolder.menulist_lv_footer.setVisibility(View.VISIBLE);
		}
		
		if( shopItem!=null && shopItem.state == 4 ){
			viewHolder.add.setVisibility(View.GONE);
		}

		return convertView;
	}

	private void onChosenGoods(ViewHolder viewHolder) {
		ChosenGoods optionGoods = viewHolder.optionGoods;
		if (viewHolder.optionGoods.getNames() != null) {
			viewHolder.cName.setText(Html.fromHtml(viewHolder.optionGoods
					.getNames()));
		}

		viewHolder.cNum.setText(viewHolder.optionGoods.getChosenNum() + "");
		viewHolder.adjust.setTag(viewHolder);
		viewHolder.cAdd.setTag(viewHolder);
		viewHolder.cMinus.setTag(viewHolder);

		// 判断这个ChosenGoods是否Goods中最后一条来显示相应的背景
		Goods goods = optionGoods.getParent();
		// List<OptionGoods> optionGoodsList = goods.getOptionGoodsList();
		List<ChosenGoods> optionGoodsList = mGoodsController.getOptionGoodsListByGId(goods.getgId());
		int size = optionGoodsList.size();
		ChosenGoods last = optionGoodsList.get(size - 1);
		if (optionGoods.equals(last)) {
			viewHolder.cMaskBottom.setVisibility(View.GONE);
		} else {
			viewHolder.cMaskBottom.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 当数据对象为Goods 显示对应的UI布局
	 * 
	 * @param position
	 * @param viewHolder
	 * @param goods
	 */
	private void onItemGoods(final int position, ViewHolder viewHolder,
			Goods goods) {
		goods.setPosition(position);
		viewHolder.goods = goods;
		changeStatus(viewHolder);
		viewHolder.iv.setImageDrawable(tu);
		// 根据goods里面的ChosenGoods是否有数据来显示相应的背景
		if (mGoodsController.hasOption(goods)) {
			List<ChosenGoods> optionGoodsList = mGoodsController
					.getOptionGoodsListByGId(goods.getgId());
			if (optionGoodsList.size() > 0) {
				viewHolder.mask.setVisibility(View.VISIBLE);
			} else {
				viewHolder.mask.setVisibility(View.GONE);
			}
		} else {
			viewHolder.mask.setVisibility(View.GONE);
			viewHolder.cMaskBottom.setVisibility(View.GONE);
		}
		refGoodsView(viewHolder);

		List<String> detailList = goods.getDetailList();
		// 根据是否有固定套餐明细来显示是否有明细按钮
		if (detailList != null && detailList.size() > 0
				&& !mGoodsController.hasOption(goods)) {
			viewHolder.detail.setVisibility(View.VISIBLE);
		} else {
			viewHolder.detail.setVisibility(View.GONE);
		}

		loadIMG(viewHolder.iv, goods);
		
		//加载爱心图片
		if(goods.getSalesUrl()!=null&&!goods.getSalesUrl().equals("")){
			Picasso.with(context).load(goods.getSalesUrl()).placeholder(tu).error(tu).into(viewHolder.heart);
		}
		
		viewHolder.name.setText(goods.getgName());
		viewHolder.price.setText(Html.fromHtml("<small>¥</small>"
				+ ParseUtils.formatPrice(goods.getPrice())
				+ "<small><font color='#666666'>/" + goods.getUnit()
				+ "</font></small>"));
		viewHolder.goodsView.setTag(viewHolder);
		viewHolder.iv.setTag(viewHolder);
		viewHolder.detail.setTag(viewHolder);
		viewHolder.choose.setTag(viewHolder);
		viewHolder.numview.setTag(viewHolder);
		viewHolder.add.setTag(viewHolder);
		viewHolder.minus.setTag(viewHolder);

	}

	private void refGoodsView(ViewHolder viewHolder) {
		// 判断商品是否暂缺
		if (viewHolder.goods.getState() == 2) {
			viewHolder.na.setVisibility(View.VISIBLE);
			viewHolder.choose.setVisibility(View.GONE);
			viewHolder.add.setVisibility(View.GONE);
			viewHolder.num.setVisibility(View.GONE);
			viewHolder.minus.setVisibility(View.GONE);
		} else {
			viewHolder.na.setVisibility(View.GONE);
			if ( shopItem!=null ) {
				// 根据店铺状态来显示相应的ui
				if (shopItem.getSpending() < 0||shopItem.getState() == 2) {
					viewHolder.choose.setVisibility(View.GONE);
					viewHolder.add.setVisibility(View.GONE);
					viewHolder.num.setVisibility(View.GONE); 
					viewHolder.minus.setVisibility(View.GONE);
				} else if (shopItem.getState() == 1 || shopItem.getState() == 3) {
					// viewHolder.add.setVisibility(View.VISIBLE);
					if (mGoodsController.hasOption(viewHolder.goods)) {
						List<ChosenGoods> list = mGoodsController
								.getOptionGoodsListByGId(viewHolder.goods.getgId());
						// 情况1 有属性
						if (list.size() >= 1) {
							viewHolder.choose.setVisibility(View.VISIBLE);
							viewHolder.add.setVisibility(View.GONE);
							viewHolder.num.setVisibility(View.GONE);
							viewHolder.minus.setVisibility(View.GONE);
						} else {
							viewHolder.choose.setVisibility(View.GONE);
							viewHolder.num.setVisibility(View.GONE);
							viewHolder.minus.setVisibility(View.GONE);
							viewHolder.add.setVisibility(View.VISIBLE);
						}
					} else {
						// 情况2 没有可选的属性
						if (viewHolder.goods.getChosenNum() >= 1) {
							viewHolder.choose.setVisibility(View.GONE);
							viewHolder.add.setVisibility(View.VISIBLE);
							viewHolder.num.setVisibility(View.VISIBLE);
							viewHolder.minus.setVisibility(View.VISIBLE);
						} else {
							viewHolder.choose.setVisibility(View.GONE);
							viewHolder.num.setVisibility(View.GONE);
							viewHolder.minus.setVisibility(View.GONE);
							viewHolder.add.setVisibility(View.VISIBLE);
						}
					}
				}
			}
			viewHolder.num.setText(viewHolder.goods.getChosenNum() + "");
		}
	}

	/**
	 * 加载图片
	 * 
	 * @param tuContainer
	 * @param item
	 */
	private void loadIMG(final ImageView img, Goods item) {
		if(item.getPicUrl()!=null&&!item.getPicUrl().equals("")){
			Picasso.with(context).load(item.getPicUrl()).placeholder(tu).error(tu).into(img);
		}
	}

	/**
	 * 控制加减号显示 隐藏
	 * 
	 * @param viewHolder
	 */
	public void changeStatus(ViewHolder viewHolder) {
		if (viewHolder.goods.getChosenNum() <= 0) {
			viewHolder.minus.setVisibility(View.GONE);
			viewHolder.num.setVisibility(View.GONE);
		} else {
			viewHolder.minus.setVisibility(View.VISIBLE);
			viewHolder.num.setVisibility(View.VISIBLE);
		}
	}

	class ViewHolder implements IViewHolder {
		int position = -1;
		// layout="@layout/include_item_goods"
		RelativeLayout goodsView;
		ImageView mask;
		ImageView iv;
		ImageView heart;
		ImageView glass;
		TextView name;
		TextView price;
		ImageView detail;
		RelativeLayout add;
		RelativeLayout numview;
		TextView num;
		RelativeLayout minus;
		ImageView choose;
		TextView na;
		Goods goods;
		// layout="@layout/include_item_chosengoods"
		RelativeLayout chosenGoodsView;
		LinearLayout adjust;// 调整
		ImageView cMaskBottom;
		TextView cName;
		ImageView cAdd;
		TextView cNum;
		ImageView cMinus;
		ChosenGoods optionGoods;
		// footer
		LinearLayout menulist_lv_footer;

		@Override
		public void load() {
			if (goods != null) {
				if (!TextUtils.isEmpty(goods.getPicUrl())) {
					loadIMG(iv, goods);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		ViewHolder viewHolder;
		Goods goods;
		ChosenGoods chosenGoods = null;
		switch (v.getId()) {
		case R.id.item_menulist_view:
			break;
		case R.id.item_menulist_lv_iv:
			viewHolder = (ViewHolder) v.getTag();
			goods = viewHolder.goods;
			if(goods.getDetailPic()!=null&&!goods.getDetailPic().equals("")){
				EventBus.getDefault().post(new EventGoodsDetails(goods.getDetailPic()));
			}
			break;
		case R.id.item_menulist_lv_detail:
			viewHolder = (ViewHolder) v.getTag();
			goods = viewHolder.goods;
			EventBus.getDefault().post(new EventShowDetails(goods));
			break;
		case R.id.item_menulist_lv_choose:
		case R.id.item_menulist_lv_add:
			viewHolder = (ViewHolder) v.getTag();
			goods = viewHolder.goods;
			if (isShowPanel(goods)) {
				// 显示商品属性
				mLayoutControl.showPropView(goods);

			} else {
				boolean hasOption = mGoodsController.hasOption(goods);
				if (!hasOption) {
					shoppingCarModel.addGoods(goods);
					EventBus.getDefault().post(new EventRefPrice());
				} else {
					try {
						Goods copy = (Goods) CloneUtils.copy(goods);
						chosenGoods = new ChosenGoods(copy);
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// 生成一行不加料
					noSeasoning(chosenGoods);
				}
				refGoodsView(viewHolder);
				mLayoutControl.checkGiftList();
			}

			break;
		case R.id.item_menulist_lv_minus:
			viewHolder = (ViewHolder) v.getTag();
			goods = viewHolder.goods;
			if (goods.getChosenNum() > 0) {
				shoppingCarModel.minusGoods(goods);
				EventBus.getDefault().post(new EventRefPrice());
			}
			refGoodsView(viewHolder);
			mLayoutControl.checkGiftList();
			break;
		case R.id.shopmenu_child_adjust:
			viewHolder = (ViewHolder) v.getTag();
			chosenGoods = viewHolder.optionGoods;
			// 显示已选好的商品属性
			mLayoutControl.showPropView(chosenGoods.getParent(), chosenGoods);
			break;
		case R.id.shopmenu_child_add:
			viewHolder = (ViewHolder) v.getTag();
			chosenGoods = viewHolder.optionGoods;
			
			// 向购物车添加数据
			shoppingCarModel.addGoods(chosenGoods);
			viewHolder.cNum.setText(chosenGoods.getChosenNum() + "");
			Log.i("calculate", "ShopMenuListAdapter 算完了");
			EventBus.getDefault().post(new EventRefPrice());
			mLayoutControl.checkGiftList();
			break;
		case R.id.shopmenu_child_minus:
			viewHolder = (ViewHolder) v.getTag();
			chosenGoods = viewHolder.optionGoods;
			// 向购物车删减数据
			shoppingCarModel.minusGoods(chosenGoods);
			if (chosenGoods.getChosenNum() == 0) {
				EventBus.getDefault().post(new EventShoppingCarChange());
			} else {
				viewHolder.cNum.setText(chosenGoods.getChosenNum() + "");
			}

			
			EventBus.getDefault().post(new EventRefPrice());
			mLayoutControl.checkGiftList();
			break;
		default:
			break;
		}
	}

	// 添加一个不加料的菜品
	private void noSeasoning(ChosenGoods chosenGoods) {
		// 不加料
		// mGoodsController.calculateInsertPos(goods, holder.position);
		chosenGoods.setNames("￥" + ParseUtils.formatPrice(chosenGoods.getPrice())+ ":不加料");
		shoppingCarModel.addGoods(chosenGoods);
		
		EventBus.getDefault().post(new EventShoppingCarChange());
		EventBus.getDefault().post(new EventRefPrice());
	}

	/**
	 * 是否显示属性面板
	 * 
	 * @param goods
	 * @return
	 */
	public boolean isShowPanel(Goods goods) {
		OptionGroup specGroup = goods.getSpecGroup();
		List<OptionGroup> optGList = goods.getOptGList();
		boolean subGRequired = goods.isSubGoodsRequired();
		if (specGroup != null) {
			return true;
		}
		if (optGList != null) {
			for (OptionGroup opg : optGList) {
				if (opg.isRequired()) {
					return true;
				}
			}
		}

		if (subGRequired) {
			return true;
		}
		return false;
	}

}
